package com.jhs.kjs.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.jhs.kjs.dto.AdminBoardPagingDTO;
import com.jhs.kjs.dto.AdminPointPagingDTO;
import com.jhs.kjs.dto.MenuDTO;
import com.jhs.kjs.service.IAdminBoardService;
import com.jhs.kjs.service.IAdminMemberService;
import com.jhs.kjs.service.IAdminPointService;
import com.jhs.kjs.service.IUserService;

@RequestMapping(value = "/m")
@Controller
public class MobileController extends CommonController{
	private static final Logger logger = LoggerFactory.getLogger(MobileController.class);
	
	@Autowired
	IUserService 		userService;
	@Autowired
	IAdminBoardService 	adminBoardService;
	@Autowired
	IAdminPointService  adminPointService;
	@Autowired
	IAdminMemberService adminMemberService;
	
	@RequestMapping(value = "/mobileMain", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView mobileMain(@ModelAttribute("paging") AdminBoardPagingDTO paging, Model model){
		List<MenuDTO> menuList = getUserBoardList();
		
		int boardMin = Integer.MAX_VALUE;
		int boardMax = 0;
		Map<String, List<AdminBoardPagingDTO>> boardResultParam = new LinkedHashMap<String, List<AdminBoardPagingDTO>>();

		for (MenuDTO menu : menuList) {
			if (menu.getMenuType() == 1 && menu.getUseFlag() == 1) {

				boardMin = Math.min(boardMin, menu.getMenuIndex());
				boardMax = Math.max(boardMax, menu.getMenuIndex());
				setBoardList(boardResultParam, menu);
			}
		}

		model.addAttribute("boardMin", boardMin);
		model.addAttribute("boardMax", boardMax);
		model.addAttribute("boardList", boardResultParam);

		model.addAttribute("userBoardList", getUserBoardList());
		return new ModelAndView("m/index");
	}
	
	private void setBoardList(Map<String, List<AdminBoardPagingDTO>> map, MenuDTO menu) {

		AdminBoardPagingDTO paging = new AdminBoardPagingDTO();
		paging.setCustom_unit(5);
		int menuIndex = menu.getMenuIndex();
		paging.setMenuIndex(menuIndex);
		List<AdminBoardPagingDTO> list = adminBoardService.getAdminBoardList(paging);
		if (list == null) {
			list = new ArrayList<AdminBoardPagingDTO>();
		}
		map.put("boardList" + menuIndex, list);
	}
	
	@RequestMapping(value = "/boardListMain", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView boardMain(@ModelAttribute("paging") AdminBoardPagingDTO paging){
		ModelAndView model = new ModelAndView();
		int menuIndex = paging.getMenuIndex();
		MenuDTO menu = getMenuInfo(menuIndex);
		
		String pageName = "";
		pageName = "m/sub_list";
		
		model.setViewName(pageName);
		model.addObject("menu", menu);
		model.addObject("menuList", getUserBoardList());
		model.addObject("totalPage", adminBoardService.getAdminBoardCount(paging));
		
		return model;
	}
	
	@RequestMapping(value = "/getBoardList", method = RequestMethod.POST)
	public String getBoardList(HttpServletRequest req, Model model, @ModelAttribute("paging") AdminBoardPagingDTO paging){
		model.addAttribute("boardList", adminBoardService.getAdminBoardList(paging));
		model.addAttribute("totalPage", adminBoardService.getAdminBoardCount(paging));
		
		return "";
	}
	
	@RequestMapping(value = "/boardView", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView boardView(HttpServletRequest req, AdminBoardPagingDTO boardDTO) throws Exception{
		Map<String, Long> param = new HashMap<String, Long>();
		int menuIndex = boardDTO.getMenuIndex();
		param.put("menuIndex", Long.parseLong(String.valueOf(menuIndex)));
		param.put("textID", Long.parseLong(String.valueOf(boardDTO.getTextID())));
		
		MenuDTO menu = getMenuInfo(menuIndex);
		ModelAndView mvc = new ModelAndView();
		String view = "";
		int menuType = menu.getMenuType();
		if (menuType == 0) {
			view = "m/sub_view";
		} else {
			view = "m/sub_view2";
		}
		
		AdminBoardPagingDTO dto = adminBoardService.getAdminBoardView(param);
		if(menuType == 1) {
			if(getUser(req).getLevel() != 40) {
				
				Map<String, String> paramMap = new HashMap<String, String>();
				
				paramMap.put("userId", getUser(req).getUserId());
				paramMap.put("textID", String.valueOf(boardDTO.getTextID()));
				paramMap.put("usePoint", String.valueOf(dto.getUsePoint()));
				String check = adminPointService.getUsePointCheck(paramMap);
				
				//사용내역 파라미터
				AdminPointPagingDTO pointDTO = new AdminPointPagingDTO();
				pointDTO.setTextID(boardDTO.getTextID());
				pointDTO.setPoint(dto.getUsePoint());
				pointDTO.setUserId(getUser(req).getUserId());
				
				adminBoardService.updateViewCnt(param);
				//사용내역에 없음
				if(check == null) {
					//게시글의 누적 포인트 증가
					adminBoardService.updateSumPoint(param);
					//사용내역 추가
					adminPointService.insertUsePoint(pointDTO);
					//사용자포인트 차감
					userService.updateUserPoint(paramMap);
				} 
			}
			mvc.addObject("provider", adminBoardService.getProvider(param));
		} else {
			//조회수 증가
			adminBoardService.updateViewCnt(param);
		}
		dto = adminBoardService.getAdminBoardView(param);
		String content = dto.getContents();
			
		content = content.replaceAll("&lt;", "<");
		content = content.replaceAll("&gt;", ">");
		
		dto.setContents(content);
		mvc.addObject("boardView", dto);
		mvc.addObject("menu", menu);
		mvc.addObject("menuList", getUserBoardList());
		mvc.addObject("textID", boardDTO.getTextID());
		mvc.addObject("nextBoardView", adminBoardService.getNextBoardView(param));
		mvc.addObject("prevBoardView", adminBoardService.getPrevBoardView(param));
		mvc.setViewName(view);
		
		return mvc;
	}
	
	//미회원 가입자 게시글 상세보기
	@RequestMapping(value = "/userBoardView", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView userBoardView(HttpServletRequest req, AdminBoardPagingDTO boardDTO) throws Exception{
		Map<String, Long> param = new HashMap<String, Long>();
		int menuIndex = boardDTO.getMenuIndex();
		param.put("menuIndex", Long.parseLong(String.valueOf(menuIndex)));
		param.put("textID", Long.parseLong(String.valueOf(boardDTO.getTextID())));
		
		MenuDTO menu = getMenuInfo(menuIndex);
		ModelAndView mvc = new ModelAndView();
		String view = "";
		AdminBoardPagingDTO dto = adminBoardService.getAdminBoardView(param);
		
		String contents = dto.getContents();
		//태그삭제
		contents = contents.replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>", "").replaceAll("\r|\n| ","");
		//3줄 노출		
		contents = contents.substring(0, contents.length() / 2);
		
		dto.setContents(contents);
		logger.debug(contents);
		
		mvc.addObject("boardView", dto);
		mvc.addObject("menu", menu);
		mvc.addObject("menuList", getUserBoardList());
		mvc.addObject("textID", boardDTO.getTextID());
		mvc.addObject("nextBoardView", adminBoardService.getNextBoardView(param));
		mvc.addObject("prevBoardView", adminBoardService.getPrevBoardView(param));
		
		view = "m/sub_userView";
		mvc.setViewName(view);
		
		return mvc;
	}
	
	@RequestMapping(value = "/login", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView signIn(HttpServletRequest request, HttpServletResponse response, Locale locale, Model model) {
		ModelAndView mvc = new ModelAndView("m/login");
		String errorMsg = request.getParameter("msg");
		if(StringUtils.equals(errorMsg, "true")){
			errorMsg = "아이디와 비밀번호를 확인해주세요.";
		}else{
			errorMsg = "";
		}
		mvc.addObject("msg", errorMsg);
		mvc.addObject("menuList", getUserBoardList());
		return mvc;
	}
}
